<template>
  <div class="page meetingSubscribe">
    <van-nav-bar
      left-arrow
      @click-left="onClickBack"
      title="会议室预约"
      fixed
      class="my-nav-bar2"
    />
    <van-form
      @submit="onSubmit"
      label-width="100px"
      style="margin-top: 46px"
      class="form"
    >
      <van-cell-group style="background-color: #ffffff00">
        <div class="card">
          <van-field
            v-model="formData.orderOrgName"
            name="orderOrgName"
            label="申请单位"
            placeholder="请选择申请单位"
            :rules="[{ required: true }]"
            required
            right-icon="arrow"
            @click="showPickerOrderOrgName = true"
          />
          <van-popup v-model="showPickerOrderOrgName" position="bottom">
            <van-tree-select
              :items="orderOrgNameOption"
              :active-id.sync="formData.orderOrg"
              @click-nav="handleChange"
              :main-active-index.sync="activeIndex"
              @click-item="handleConfirmOrderOrgName"
            />
          </van-popup>
          <van-field
            v-model="formData.meetTitle"
            name="meetTitle"
            label="会议名称"
            placeholder="请选择会议名称"
            :rules="[{ required: true }]"
            required
          />
        </div>
        <div class="card">
          <van-field
            readonly
            clickable
            name="orderDate"
            :value="formData.orderDate"
            placeholder="请选择日期"
            @click="showPickerDate = true"
            right-icon="arrow"
          />
          <van-popup v-model="showPickerDate" position="bottom">
            <van-datetime-picker
              type="date"
              title="选择年月日"
              @confirm="onConfirmShowPickerDate"
              :min-date="new Date()"
              :max-date="$dayjs().add(6, 'day').toDate()"
            />
          </van-popup>

          <div class="card-content">
            <div
              class="card-content-item"
              v-for="(item, index) in roomListTime"
              :key="index"
            >
              <div
                class="card-content-item-room"
                v-for="(item2, index2) in item.roomList"
                :key="index2"
                :style="{
                  backgroundColor:
                    item2.checked == 1
                      ? '#ECF3FE'
                      : item2.checked == 2
                      ? '#2C70F4'
                      : '#fd6230',
                }"
                @click="handleTimeClick(item2, index, index2)"
              ></div>
              <span
                class="startTime"
                :style="{ color: !item.startChecked ? '#2C70F4' : '#fd6230' }"
                >{{ item.startTime }}</span
              >
              <span
                class="endTime"
                :style="{ color: !item.endChecked ? '#2C70F4' : '#fd6230' }"
                >{{ item.endTime }}</span
              >
            </div>
          </div>
        </div>
        <div class="card">
          <van-field v-model="formData.meetPersons" name="meetPersons" label="参会人数" :placeholder="this.$route.params?handlePlaceholder():''" 
            type="digit" :rules="this.meetData?.roomSeatNum > 2 ? rules1: rules2" />

          <van-field
            :value="formData.meetType"
            name="meetType"
            label="会议类型"
            placeholder="请选择会议类型"
            readonly
            right-icon="arrow"
            clickable
            @click="showPickerMeettingType = true"
          />

          <van-popup v-model="showPickerMeettingType" position="bottom">
            <van-picker
              show-toolbar
              :columns="meetTypeOption"
              @confirm="onConfirmMeetting"
              @cancel="showPickerMeettingType = false"
            />
          </van-popup>
        </div>
        <div class="card">
          <van-field
            required
            v-model="formData.meettingTitle"
            name="meettingTitle"
            label="会议标题"
            placeholder=" 请输入会议标题"
            :rules="[{ required: true}]"
          />
          <van-field
            required
            v-model="formData.meetItems"
            name="meetItems"
            label="物品需求"
            placeholder="请选择物品需求"
            :rules="[{ required: true}]"
            readonly
            clickable
            right-icon="arrow"
            @click="showPickerThingDemand = true"
          />

          <van-field
            v-model="formData.meetOthers"
            name="meetOthers"
            label="其他需求"
            placeholder="请输入其他需求"
          />
          <van-field
            required
            v-model="formData.meetManager"
            name="meetManager"
            label="会议负责人"
            placeholder="请选择会议负责人"
            :rules="[{ required: true}]"
            readonly
            clickable
            right-icon="arrow"
            @click="showPickerChargePerson = true"
          />

          <van-popup
            v-model="showPickerChargePerson"
            position="bottom"
            close-icon-position="top-right"
            :closeable="!Boolean(chargePersonOption.length > 0)"
          >
            <van-picker
              show-toolbar
              :columns="chargePersonOption"
              @confirm="onConfirmChargePerson"
              v-if="chargePersonOption.length > 0"
              @cancel="showPickerChargePerson = false"
            />

            <van-empty v-else description="暂无数据" />
          </van-popup>
          <van-field
            required
            v-model="formData.meetManagerPhone"
            name="meetManagerPhone"
            label="负责人联系方式"
            placeholder="请输入负责人联系方式"
            :rules="[{ required: true }]"
          />

          <van-field name="meetFiles" label="会议附件(word/pdf):">
            <template #input>
              <van-uploader
                v-model="formData.meetFiles"
                :before-read="beforeRead"
                :after-read="afterRead"
                accept=".doc,.docx,.pdf"
                list-type="picture-card"
              >
                <!-- 关键：preview-cover 插槽，替换文件预览的默认图标 -->
                <template #preview-cover="props">
                  <!-- 根据文件类型显示对应图标 -->
                  <img
                    :src="getFileIcon(props.file)"
                    class="custom-file-icon"
                    alt="文件图标"
                  />
                  <!-- 可选：显示文件名 -->
                  <div class="file-name">{{ props.file.name }}</div>
                </template>
              </van-uploader>
            </template>
          </van-field>
        </div>
      </van-cell-group>

      <van-button type="info" native-type="submit" class="btn" block round
        >下一步</van-button
      >
    </van-form>
    <selectMultiple
      v-if="showPickerThingDemand"
      :optios="thingDemandOption"
      :ids="formData.meetItemsId"
      @close="onConfirmThingDemand"
    />
  </div>
</template>
<script>
import { roomList } from "./roomlist.js";
import selectMultiple from "@/components/selectMultiple";
import { fileuploadUrl, fileShowUrl } from "@/utils/Axios";
export default {
  name: "meetingSubscribe",
  components: { selectMultiple },
  data() {
    return {
      showPickerDate: false,
      showPickerOrderOrgName: false,
      showPickerMeettingType: false,
      showPickerThingDemand: false,
      showPickerChargePerson: false,
      activeIndex: null, //申请单位选中的索引
      formData: {
        meetTitle: "",
        orderOrgName: "",
        orderUserId: "",
        meetPersons: "",
        meetType: "",
        meetTypeId: "",
        meettingTitle: "",
        meetItems: "",
        meetItemsId: "",
        meetOthers: "",
        meetManager: "",
        meetManagerId: "",
        meetManagerPhone: "",
        orderDate: this.$dayjs().format("YYYY-MM-DD"),
        sysOrgCode: "",
        meetRoomId: "",
      },
      roomListTime: [],
      meetTypeOption: [], // 会议类型
      orderOrgNameOption: [], // 申请单位
      thingDemandOption: [], // 物品需求
      chargePersonOption: [], // 会议负责人
      meetData: {},
      startTime: "",
      endTime: "",
      // 已完成的时间段列表（每个对象包含start和end时间） checked 为3 预约只能单个时间段
      ranges: {
        startTime: null,
        endTime: null,
      },
      // 已经被预约的 checked 为2  （每个对象包含start和end时间） 被预约的是多个时间段
      selectRanges: [
        {
          startTime: "09:00",
          endTime: "10:00",
        },
        {
          startTime: "14:00",
          endTime: "16:00",
        },
      ],
      // 校验 meetPersons 是否在 2 到 会议房间人数 的范围内
     
      rules1: [
        {
          validator: (value) => {
            const num = parseInt(value, 10);
            if (value == "") {
              return true;
            }
            if (!this.$route.params?.roomSeatNum) {
              return !isNaN(num) && num >= 2;
            }
            return !isNaN(num) && num >= 2 && num <= this.$route.params?.roomSeatNum;
          },
          message: !this.$route.params?.roomSeatNum ?"参会人须是 2 人以上":`参会人数必须在 2 到 ${this.$route.params?.roomSeatNum} 之间`
        }
      ],
      rules2: [
        {
          validator: (value) => value == 2,
          message: `参会人须是 2 人`
        }
      ],
    };
  },
  mounted() {
    // 模拟预约 (正式情况下， 注意selectRanges赋值就好)
    this.roomListTime = this.setYueYu(roomList);
    // this.roomListTime = roomList;

    // this.$route.params
    if (this.$route.params.id) {
      this.meetData = this.$route.params;
      const thingDemandOption = [];
      const roomEquipmentsNames =
        this.meetData.roomEquipmentsName?.split?.("、") || [];
      const roomEquipmentsId =
        this.meetData.roomEquipmentsId?.split?.(",") || [];
      roomEquipmentsNames?.forEach((item, index) => {
        thingDemandOption.push({
          id: roomEquipmentsId[index],
          name: item,
        });
      });
      console.log(this.meetData, "meetData");
      this.formData.meetFiles = [];
      this.formData.meetRoomId = this.meetData.id;
      this.formData.sysOrgCode = this.meetData.sysOrgCode;
      console.log(thingDemandOption, "thingDemandOption");
      this.thingDemandOption = thingDemandOption;
    }
    // this.formData = { ...this.$route.params}
    this.handleGetOptios();
  },
  methods: {
    getFileIcon(file) {
      const suffix = file.name.split(".").pop().toLowerCase();
      if (["doc", "docx"].includes(suffix)) {
        return require("@/assets/images/word.png"); // 文档图标
      }

      if (["pdf"].includes(suffix)) {
        return require("@/assets/images/pdf.png"); // 文档图标
      }
    },
    // 设置已经被预约的
    setYueYu(data) {
      const selectRanges = this.selectRanges;
      console.log(selectRanges, "selectRanges...");
      let rlt = [];
      if (selectRanges.length > 0) {
        rlt = data.map((p) => {
          p.roomList.map((c) => {
            selectRanges.forEach((t) => {
              if (this.isTimeInGuDingRange(c.endTime, t.startTime, t.endTime)) {
                c.checked = 2;
              }
            });
            return c;
          });
          return p;
        });
      }
      return rlt;
    },
    // 设置预约
    setYueYuIng(data) {
      const selectRanges = this.ranges;
      let rlt = [];
      rlt = data.map((p) => {
        p.roomList.map((c) => {
          if (
            this.isTimeInGuDingRange(
              c.endTime,
              selectRanges.startTime,
              selectRanges.endTime
            )
          ) {
            c.checked = 3;
          }
        });
        return p;
      });
      return rlt;
    },
    // 设置预约
    clearYueYuIng(data) {
      const selectRanges = this.ranges;
      let rlt = [];
      rlt = data.map((p) => {
        p.roomList.map((c) => {
          if (
            this.isTimeInGuDingRange(
              c.endTime,
              selectRanges.startTime,
              selectRanges.endTime
            )
          ) {
            c.checked = 1;
          }
        });
        return p;
      });
      return rlt;
    },
    /**
     * 时间转分钟数（用于比较）
     */
    timeToMinutes(time) {
      console.log(time, "time...........");
      const [hour, minute] = time.split(":").map(Number);
      return hour * 60 + minute;
    },
    /**
     * 检查时间是否在具体某个范围内
     */
    isTimeInGuDingRange(time, startTime, endTime) {
      const targetMin = this.timeToMinutes(time);
      const startMin = this.timeToMinutes(startTime);
      const endMin = this.timeToMinutes(endTime);
      return targetMin >= startMin && targetMin <= endMin;
    },
    // 是否被预约
    isBeYuYue(item) {
      if (item.checked === 2) {
        return false;
      }
      return true;
    },
    /**
     * 处理时间块点击
     */
    handleTimeClick(item, parentIndex, childIndex) {
      // 先判断时间是否在预约内
      if (!this.isBeYuYue(item)) {
        return;
      }

      // 是否已经在选中的范围内
      const time = item.endTime;
      let startTime = null;
      let endTime = null;
      let isInSelect = false;
      let roomList = [];
      // 还没有选中
      if (this.ranges.startTime == null && this.ranges.endTime == null) {
        this.ranges.startTime = time;
        this.roomListTime[parentIndex].roomList[childIndex].checked = 3;
        return;
      }
      // 已经选了开始时间,结束时间没选，这个时候，需要判断结束时间是否大于开始时间
      if (this.ranges.startTime != null && this.ranges.endTime == null) {
        startTime = this.timeToMinutes(this.ranges.startTime);
        endTime = this.timeToMinutes(time);
        if (startTime >= endTime) {
          this.$toast("请点击正确的结束时间");
          return;
        } else {
          // 看是否在已经被预约的时间内
          isInSelect = false;
          this.selectRanges.forEach((t) => {
            if (this.isTimeInGuDingRange(time, t.startTime, t.endTime)) {
              isInSelect = true;
            }
          });
          if (isInSelect) {
            this.$toast("结束时间在已经被预约的时间内，请点击正确的结束时间");
            return;
          }
          this.ranges.endTime = time;
          // 设置一段时间内的时间被选中
          roomList = this.setYueYuIng(this.roomListTime);
          this.roomListTime = roomList;
          return;
        }
      }
      // 两个时间都选中的情况下
      if (this.ranges.startTime != null && this.ranges.endTime != null) {
        // 看是否在已经被预约的时间内
        isInSelect = false;
        this.selectRanges.forEach((t) => {
          if (this.isTimeInGuDingRange(time, t.startTime, t.endTime)) {
            isInSelect = true;
          }
        });
        if (isInSelect) {
          this.$toast("已经被预约的时间，无法再被预约");
          return;
        }
        // 先清空已经预约的
        roomList = this.clearYueYuIng(this.roomListTime);
        this.ranges.startTime = time;
        // 重新选择，直接去掉结束时间
        this.ranges.endTime = null;
        roomList[parentIndex].roomList[childIndex].checked = 3;
        this.roomListTime = roomList;
        return;
      }
    },

    // handlRules: () => {
    //   const roomSeatNum = this.$route.params?.roomSeatNum
    //   if (!roomSeatNum) {
    //     return [{validator: (value) => value > 2}]
    //   }
    //   if (roomSeatNum == 2) {
    //     return [{validator: (value) => value == 2}]
    //   }
    //   if (roomSeatNum > 2) {
    //     return [{
    //         validator: (value) => {
    //           const num = parseInt(value, 10);
    //           if (value == "") {
    //             return true;
    //           }
    //         return !isNaN(num) && num >= 2 && num <= roomSeatNum;
    //         },
    //       }]

    //   }
     
    // },
    handlePlaceholder() { 
      const roomSeatNum = this.$route.params?.roomSeatNum
      if (!roomSeatNum) {
        return "参会人数须是 2 人以上"
      }
      if (roomSeatNum == 2) {
        return "参会人数须是 2 人"
      }
      if (roomSeatNum  > 2) {
        return `参会人数须在 2 到 ${roomSeatNum} 之间`
      }
    },
    // 选择取消时间
    handleChecked(index, index2) {
      console.log(index, index2, this.roomListTime);
      if (this.roomListTime[index].roomList[index2].checked === 2) {
        return;
      }
      // if (this.roomListTime[index].roomList[index2].checked === 1) {
      //   let startTime = []
      //   for (let i = 0; i < this.roomListTime.length; i++) {
      //     for (let i2 = 0; i2 < this.roomListTime[i].roomList.length; i2++) {
      //       if (this.roomListTime[i].roomList[i2].checked === 3 && !startTime.length) {
      //         startTime = [i, i2]
      //         break
      //       }
      //     }
      //   }
      //   if (startTime.length) {

      //     const roomListTime = JSON.parse(JSON.stringify(this.roomListTime))
      //     this.roomListTime = roomListTime.map((item, Index1) => {
      //       item.roomList.map((item2,Index2) => {
      //         if (Index1 >= startTime[0] && Index1 < index) {
      //           if (Index2 >= startTime[2]) {
      //             return { ...item2, checked: 3 }
      //           } else {
      //             return item2
      //           }
      //         } else if (Index1 === index){
      //           if (Index2 <= index2) {
      //             return { ...item2, checked: 3 }
      //           } else {
      //             return item2
      //           }
      //         }
      //         return item2
      //       })
      //       return item
      //     })
      //     return
      //   }

      // }

      this.roomListTime[index].roomList[index2].checked =
        this.roomListTime[index].roomList[index2].checked === 1 ? 3 : 1;
      this.roomListTime[index].startChecked = this.roomListTime[
        index
      ].roomList.some((item) => item.checked === 3);
      this.roomListTime[index].endChecked = this.roomListTime[
        index
      ].roomList.every((item) => item.checked === 3);
    },
    // 获取下拉数据
    handleGetOptios() {
      console.log("this.$route.params", this.$route.params);
      // 获取会议类型字典值
      this.$axios(
        {
          url: "/sys/api/getManyDictItems?dictCodeList=meet_type",
          method: "post",
        },
        { returnAllData: true }
      ).then((res) => {
        console.log("resmeetting", res);
        this.meetTypeOption = res?.meet_type || [];
      });
      // 获取申请单位数据
      this.$axios({ url: "/sys/sysDepart/queryDepartTreeSync" }).then((res) => {
        console.log("resorderOrgNameOption", res);
        this.orderOrgNameOption =
          res?.map((item) => ({ ...item, text: item.departName })) || [];
        this.handleChange(0);
        console.log("this.orderOrgNameOption", this.orderOrgNameOption);
      });
      //
      // this.chargePersonOption = this.chargePersonOption.concat(this.chargePersonOption)
      // this.meetTypeOption = this.meetTypeOption.concat(this.meetTypeOption)
    },
    // 根据上级部门id查下级部门
    handleChange(index) {
      console.log("index", index);
      if (!this.orderOrgNameOption[index].isLeaf) {
        this.$axios({
          url: `/sys/sysDepart/queryDepartTreeSync?pid=${this.orderOrgNameOption[index].id}`,
        }).then((res) => {
          console.log("resorderOrgNameOption", res);
          const children =
            res?.map((item) => ({ ...item, text: item.departName })) || [];
          this.orderOrgNameOption[index].children = children;
          this.orderOrgNameOption = [...this.orderOrgNameOption];
          console.log("this.orderOrgNameOption2222", this.orderOrgNameOption);
        });
      }
    },
    onClickBack() {
      this.$router.push("/meetingSubscribe");
    },
    // 选择单位
    handleConfirmOrderOrgName(values) {
      console.log("values", values);
      this.formData.orderOrgName = values.departName;
      console.log("this.formData", this.formData);
      this.showPickerOrderOrgName = false;
      this.$axios({ url: `/sys/user/queryUserByDepId?id=${values.id}` }).then(
        (res) => {
          this.chargePersonOption = res.map((item) => ({
            ...item,
            text: item.realname,
          }));
        }
      );
    },
    // 选择会议时间（小时）
    handleChooseHour(data) {
      console.log("data", data);
    },
    // 时间选择
    onConfirmShowPickerDate(time) {
      // this.formData.date = time;
      this.formData.date = this.$dayjs(time).format("YYYY-MM-DD");
      this.showPickerDate = false;
    },
    // 物品选择
    onConfirmThing(data) {
      this.showPicker = false;
      if (!data) return;
      console.log("data", data);
      this.formData.roomMamagersId = data.id;
      this.formData.roomManagers = data.name;
    },
    // 提交预约申请
    onSubmit(values) {
      console.log("values", values);
      console.log("formData", this.formData);

      const postData = {
        ...this.formData,
        orderStartTime:
          this.$dayjs(values.orderStartTime).format("YYYY-MM-DD") + " 11:00:00",
        orderEndTime:
          this.$dayjs(values.orderStartTime).format("YYYY-MM-DD") + " 13:00:00",
        meetFiles: this.formData.meetFiles?.join(","),
      };
      delete postData.orderDate;
      console.log("postData", postData);
      this.$axios({
        url: `/roomOrder/add`,
        method: "post",
        data: postData,
      }).then((res) => {
        if (res) {
          this.$toast.success(res || "操作成功");
          this.$router.push({
            name: "subscribeList",
            params: { active: "3" }, // 去预约列表 已发起列表
          }); // 去预约列表
        }
      });
    },
    // 物品需求
    onConfirmThingDemand(data) {
      this.showPickerThingDemand = false;
      if (!data) return;
      this.formData.meetItemsId = data.id;
      this.formData.meetItems = data.name;
    },
    // 会议类型
    onConfirmMeetting(data) {
      console.log("data", data);
      this.formData.meetType = data.label;
      this.formData.meetTypeId = data.value;
      this.showPickerMeettingType = false;
    },
    // 会议负责人
    onConfirmChargePerson(data) {
      this.formData.meetManagerId = data.id;
      this.formData.meetManager = data.realname;
      this.formData.meetManagerPhone = data.phone || data.telephone;
      this.showPickerChargePerson = false;
    },
    // 上传之前
    beforeRead(file) {
      console.log("file", file);
      // const allowedTypes = ["doc", "docx", "pdf", "dot", "dotx", "rtf", "txt"];
      const allowedTypes = ["doc", "docx", "pdf"];
      if (!allowedTypes.some((item) => file.type.includes(item))) {
        this.$Toast("请上传word/pdf附件");
        return false;
      }
      if (!this.isAllowedFileType(file, allowedTypes)) {
        // this.$toast("请上传 doc, docx, pdf, dot, dotx, rtf 或 txt 格式的文件");
        this.$toast("请上传 doc, docx, pdf格式的文件");
        return false;
      }
      return true;
    },
    // 上传之后
    afterRead(file, fIndex) {
      console.log("file", fIndex, file);
      file.status = "uploading";
      file.message = "上传中...";
      const formData = new FormData();
      formData.append("file", file.file);
      formData.append("biz", "temp");
      this.$axios(
        {
          specialUrl: fileuploadUrl,
          method: "post",
          data: formData,
          headers: {
            "Content-Type": "multipart/form-data",
          },
        },
        { callbackFile: (response) => response.data }
      )
        .then((res) => {
          file.status = "done";
          this.formData.meetFiles[
            fIndex.index
          ].url = `${fileShowUrl}${res.message}`;
          file.message = "上传成功";
        })
        .catch(() => {
          file.status = "failed";
          file.message = "上传失败";
        });
    },
    isAllowedFileType(file, allowedTypes) {
      const fileName = file.name;
      const fileExtension = fileName.split(".").pop().toLowerCase();
      return allowedTypes.includes(fileExtension);
    },
  },
};
</script>
<style scoped lang="less">
.meetingSubscribe {
  padding-top: 2px;
  background: linear-gradient(115deg, #f7faff 0%, #b8d3fa 85%, #dce9fd 100%);
  backdrop-filter: blur(0px);
  padding-bottom: 40px;
  overflow: hidden;
  .my-nav-bar2 {
    background-color: transparent;
  }
  .form {
    padding: 10px 15px 15px;
    height: calc(100% - 11px);
    overflow: auto;
    .card {
      padding: 10px;
      background: #fff;
      border-radius: 10px;
      width: 100%;
      /* 重要 */
      overflow-x: auto;
      margin-bottom: 10px;

      .card-content {
        display: flex;
        gap: 10px;
        overflow-x: auto;
        // white-space: nowrap;
        width: 100%;
        /* 重要 */
        -webkit-overflow-scrolling: touch;

        .card-content-item {
          position: relative;
          display: flex;
          flex-direction: column;
          justify-content: space-between;
          gap: 2px;
          color: #2c70f4;
          font-size: 14px;
          padding: 17px 0;

          .startTime {
            position: absolute;
            top: 0;
            left: 0;
            background-color: #fff;
          }

          .endTime {
            position: absolute;
            bottom: 0;
            left: 0;
            background-color: #fff;
          }

          .card-content-item-room {
            background-color: #2c70f4;
            width: 35px;
            height: 35px;
          }
        }
      }
    }

    .btn {
      margin: 20px 0;
    }
  }

  /* 自定义图标样式：适配卡片布局 */
  .custom-file-icon {
    width: 32px;
    height: 32px;
    margin: 10px 24px;
    background: #f5f5f5;
  }
  /* 文件名样式：叠加在图标下方或上方 */
  .file-name {
    position: absolute;
    bottom: 0;
    left: 0;
    right: 0;
    padding: 4px;
    font-size: 12px;
    color: #333;
    background: #f5f5f5;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    text-align: center;
  }
  /* 上传按钮样式（可选） */
  .upload-btn {
    width: 100%;
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    border: 1px dashed #ccc;
    border-radius: 8px;
    color: #999;
  }
}
</style>